//
//  ZYCStuLeavePersonViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/15.
//

#import "ZYCStuLeavePersonViewController.h"
#import "ZYCRoleTreeModel.h"
#import "ZYCStuLeavePersonCell.h"
#import "ZYCStuLeaveDeptCell.h"
#import "ZYCSearchBarView.h"
#import "ZYCProtalSendNoticeViewController.h"
#import "ZYCNavigationController.h"
#import "ZYCStudentLeaveViewController.h"
#import "ZYCLeaveRecordSearchView.h"
#import "UIButton+EnlargeEdge.h"
#import "ZYCFliterSingleChoiceView.h"
@interface ZYCStuLeavePersonViewController ()<UITableViewDataSource,UITableViewDelegate,ZYCSearchBarViewDelegate>
{
    NSIndexPath *selectIndexPath;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZYCSearchBarView *searchView;
@property (nonatomic, strong) UIButton *comfirmButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) NSMutableArray *selectArr;
// 总人数
@property (nonatomic, strong) NSArray *totalArray;
//搜索人数
@property (nonatomic, strong) NSArray *searchResultArray;

@property (nonatomic, strong) ZYCRoleTreeModel *selectModel;

@property (nonatomic, strong) ZYCFliterSingleChoiceView *fliterView;
@property (nonatomic, copy) NSString *keyword;


@end

@implementation ZYCStuLeavePersonViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.titleString;
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.tableView];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.comfirmButton];

    self.totalArray = [self filterSource:self.dataSource type:@"4"];
    self.searchResultArray = self.totalArray ;
    self.fliterView.dataSource = self.searchResultArray;

    
    [self loadStudentTree];
}

- (void)loadStudentTree{
    [MrjSVProgressHUD showWithStatus:@"加载中"];
    [[URLManager sharedURLManager] getUrlString:Common_Get_QueryStudent requestService:RequestServiceSystem parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array =  [NSArray yy_modelArrayWithClass:[ZYCRoleTreeModel class] json:responseObject[@"body"]];
                self.dataSource = array;
                [self.tableView reloadData];
            }
        } failure:^(NSError * _Nonnull error) {

        }];
}



 //递归思想
- (NSArray *)filterSource:(NSArray *)sourceArray type:(NSString *)type{
    if (sourceArray.count == 0)  return nil;
    NSMutableArray *mArr = [NSMutableArray arrayWithCapacity:0];
    for (ZYCRoleTreeModel *model in sourceArray) {
        if ([model.dateType isEqualToString:type]) {
            [mArr addObject:model];
        }
        NSArray *temp = [self filterSource:model.children type:type];
        if (temp.count > 0) {
            [mArr addObjectsFromArray:temp];
        }
    }
    return mArr.copy;
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCRoleTreeModel *model = self.dataSource[indexPath.row];
    if ([model.dateType integerValue] == 4) {
        ZYCStuLeavePersonCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCStuLeavePersonCell class]) forIndexPath:indexPath];
        cell.model = model;
        if (selectIndexPath == indexPath) {
            cell.isSelect = YES;
        }else{
            cell.isSelect = NO;
        }
        return cell;
    }else{
        ZYCStuLeaveDeptCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCStuLeaveDeptCell class]) forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZYCRoleTreeModel *model = self.dataSource[indexPath.row];
    if ([model.dateType integerValue] == 4) {
        ZYCStuLeavePersonCell *cell = [tableView cellForRowAtIndexPath:selectIndexPath];
        cell.isSelect = NO;
        selectIndexPath = indexPath;
        self.selectModel = model;
        [self.tableView reloadData];
    }else{
//        ZYCStuLeavePersonViewController *vc = [ZYCStuLeavePersonViewController new];
        self.dataSource = model.children;
        self.titleString = model.label;
        [self.tableView reloadData];
//        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *v = [[UIView alloc] init];
    v.backgroundColor =  HEX_RGB(@"#F9F9F9");
    return v;
}


#pragma mark - ZYCSearchBarViewDelegate
- (void)searchBarViewDidTextDidChange:(NSString *)searchText height:(CGFloat)height{
    self.fliterView.frame = CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame) - height);
    NSLog(@"搜索关键字:%@",searchText);
    self.keyword = searchText;
    if (searchText.length > 0) {
        self.fliterView.hidden = NO;
        
    }else{
        self.fliterView.hidden = YES;
    }
}


//- (void)searchBarViewDidTextDidChange:(NSString *)searchText{
//    if (searchText.length == 0) {
//        _searchActive = NO;
//        [self.searchStudentView reload];
//        return;
//    }
//    _searchActive = YES;
//    _requltData = [NSMutableArray array];
//    _requltIndexData = [NSMutableArray array];
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
//    dispatch_async(globalQueue, ^{
//        [self.tableData enumerateObjectsUsingBlock:^(NSMutableArray *obj, NSUInteger adx, BOOL * _Nonnull stop) {
//            if (self.requltData.count == 0 || [[self.requltData lastObject] count] != 0) {
//                [self.requltData addObject:[NSMutableArray array]];
//            }
//            [obj enumerateObjectsUsingBlock:^(ZYCRoleTreeModel *stu, NSUInteger idx, BOOL * _Nonnull stop) {
//                NSString *tempStr = stu.label;
//                NSString *pinyin = [self transformToPinyin:tempStr isQuanpin:NO];
//
//                if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0) {
//                    [self.requltData.lastObject addObject:stu];
//                    if (self.requltIndexData == 0 || ![self.requltIndexData.lastObject isEqualToString:self.tableIndexData[adx]]) {
//                        [self.requltIndexData addObject:self.tableIndexData[adx]];
//                    }
//                }
//
//            }];
//        }];
//        if ([self.requltData.lastObject count] == 0) {
//            [self.requltData removeLastObject];
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.searchStudentView.searchActive = self.searchActive;
//            self.searchStudentView.tableData = self.tableData;
//            self.searchStudentView.requltData = self.requltData;
//            self.searchStudentView.tableIndexData = self.tableIndexData;
//            self.searchStudentView.requltIndexData = self.requltIndexData;
//            [self.searchStudentView reload];
//        });
//
//    });
//}


#pragma mark - setters

- (void)setKeyword:(NSString *)keyword{
    _keyword = keyword;
    if (!keyword || keyword.length <= 0) {
        self.searchResultArray = self.totalArray;
    }else{
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"label contains[c] %@", keyword];
        self.searchResultArray = [self.totalArray filteredArrayUsingPredicate:filterPredicate];
    }
    self.fliterView.dataSource = self.searchResultArray;
    [self.fliterView refresh];
}
#pragma mark - getters
- (NSMutableArray *)selectArr {
    if (!_selectArr) {
        _selectArr = [[NSMutableArray alloc] init];
    }
    return _selectArr;
}

- (ZYCSearchBarView *)searchView {
    if (!_searchView) {
        _searchView = [[ZYCSearchBarView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 63.0f)];
        _searchView.delegate = self;
    }
    return _searchView;
}

- (ZYCFliterSingleChoiceView *)fliterView {
    ZYCWeakSelf
    if (!_fliterView) {
        _fliterView = [[ZYCFliterSingleChoiceView alloc] initWithFrame:self.tableView.frame];
        _fliterView.hidden = YES;
        _fliterView.selectStuBlock = ^(ZYCRoleTreeModel * _Nonnull model) {
            weakSelf.selectModel = model;
        };
        [self.view addSubview:_fliterView];
    }
    return _fliterView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCStuLeavePersonCell class] forCellReuseIdentifier:NSStringFromClass([ZYCStuLeavePersonCell class])];
        [_tableView registerClass:[ZYCStuLeaveDeptCell class] forCellReuseIdentifier:NSStringFromClass([ZYCStuLeaveDeptCell class])];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

//- (ZYCLeaveRecordSearchView *)searchStudentView {
//    ZYCWeakSelf
//    if (!_searchStudentView) {
//        _searchStudentView = [[ZYCLeaveRecordSearchView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame))];
//        _searchStudentView.hidden = YES;
//        _searchStudentView.selectStuBlock = ^(ZYCRoleTreeModel * _Nonnull model) {
//            weakSelf.selectModel = model;
//        };
//        [self.view addSubview:_searchStudentView];
//    }
//    return _searchStudentView;
//}



- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSArray alloc] init];
    }
    return _dataSource;
}

- (UIButton *)comfirmButton {
    if (!_comfirmButton) {
        _comfirmButton = [[UIButton alloc] init];
        [_comfirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [_comfirmButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _comfirmButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_comfirmButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _comfirmButton;
}




- (void)clickRightItem:(UIButton *)sender{
//    if (!self.selectModel) {
//        [MrjToast makeToast:@"请选择请假学生" makeView:self.view];
//        return;
//    }
    
    if (self.selectStudentBlock) {
        self.selectStudentBlock(self.selectModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:YES completion:^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"kTestNotificationName" object:nil userInfo:@{@"userName":self.selectModel.label,@"userId":self.selectModel.r_id}];
//    }];

}


/**
 将传进来的数据模型分组并排序  分成若干个分组  每个分组也进行排序 并删除分组中为空的分组

 @param objects 初始的对象数组
 @param selector 属性名称
 @param empty 清空与否
 @return 返回一个大数组 数组中是小数组  小数组中存储模型对象
 */
//-(NSArray *)groupingSortingWithObjects:(NSArray *)objects withSelector:(SEL)selector isEmptyArray:(BOOL)empty{
//
//    //UILocalizedIndexedCollation的分组排序建立在对对象的操作之上
//    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//
//    //得到collation索引数量（26个字母和1个#）
//    NSMutableArray *indexArray = [NSMutableArray arrayWithArray:collation.sectionTitles];
//    NSUInteger sectionNumber = [indexArray count];//sectionNumber = 27
//
//    //建立每个section数组
//    NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:sectionNumber];
//    for (int index = 0; index < sectionNumber; index++) {
//        NSMutableArray *subArray = [NSMutableArray array];
//        [sectionArray addObject:subArray];
//    }
//
//    for (ZYCRoleTreeModel *model in objects) {
//        //根绝SEL方法返回的字符串判断对象应该处于哪个分区
//        //将每个人按name分到某个section下
//        NSInteger index = [collation sectionForObject:model collationStringSelector:selector];//获取name属性的值所在的位置，比如“林”首字母是L,则就把林放在L组中
//        NSMutableArray *tempArray = sectionArray[index];
//        [tempArray addObject:model];
//    }
//
//    //对每个section中的数组按照name属性排序
//    for (NSMutableArray *arr in sectionArray) {
//        NSArray *sortArr = [collation sortedArrayFromArray:arr collationStringSelector:selector];
//        [arr removeAllObjects];
//        [arr addObjectsFromArray:sortArr];
//    }
//
//    //是不是删除空数组
//    if (empty) {
//        [sectionArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSArray *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if (obj.count == 0) {
//                [sectionArray removeObjectAtIndex:idx];
//                [indexArray removeObjectAtIndex:idx];
//            }
//        }];
//    }
//    //第一个数组为tableView的数据源  第二个数组为索引数组 A B C......
//    return @[sectionArray,indexArray];
//}

//-(NSString *)transformToPinyin:(NSString *)originalString isQuanpin:(BOOL)quanpin{
//    NSMutableString *muStr = [NSMutableString stringWithString:originalString];
//    //汉字转成拼音
//    CFStringTransform((CFMutableStringRef)muStr, NULL, kCFStringTransformMandarinLatin, NO);
//    //去掉音标
//    CFStringTransform((CFMutableStringRef)muStr, NULL, kCFStringTransformStripDiacritics, NO);
//    NSArray *pinyinArray = [muStr componentsSeparatedByString:@" "];
//    NSMutableString *allString = [NSMutableString new];
//    if (quanpin) {
//        int count = 0;
//        for (int i = 0; i < pinyinArray.count; i++)
//        {
//
//            for (int i = 0; i < pinyinArray.count; i++) {
//                if (i == count)
//                {
//                    [allString appendString:@"#"];
//                }
//                [allString appendFormat:@"%@",pinyinArray[i]];
//            }
//
//            [allString appendString:@","];
//            count++;
//        }
//    }
//    NSMutableString *initialStr = [NSMutableString new];
//    for (NSString *str in pinyinArray) {
//        if ([str length] > 0) {
//            [initialStr appendString:[str substringFromIndex:1]];
//        }
//    }
//    [allString appendFormat:@"#%@",initialStr];
//    [allString appendFormat:@",#%@",originalString];
//    return allString;
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
